/**
 *
 */
var log4js = require('log4js');
var jsonfile = require('jsonfile');
module.exports = function(RED) {
    function logger(config) {
        RED.nodes.createNode(this,config);
        var flowContext = this.context().flow;
        var node = this;
        this.config = config.config || "/node-red/gw/config/log4js.json";
        this.message = config.message || "/node-red/gw/config/message.json";

// log4js.configure("./" + this.config,{ reloadSecs: 300 })
        log4js.configure(this.config,[])

        var errlogger = log4js.getLogger("error");
        var debuglogger = log4js.getLogger("debug");
        var tracelogger = log4js.getLogger("trace");

        String.prototype.format = function(args) {
	        var s = this;
	        if (args &&　typeof (args) == "object" && !isNaN(args.length)) {
		        for (var i = 0; i < args.length; i++) {
		        	s=s.replace(new RegExp("({)" + i + "(})", "g"), args[i]);
		        }
	        } else if (args) {
	        	s=s.replace(new RegExp("({)0(})", "g"), args);
	        }
	        return s.toString();
        };

        try{
    		var messagedata = jsonfile.readFileSync(this.message);
    		var logMsg = function (level, msgCode, msgParam) {
    			if (!msgCode) {
    			  errlogger.error(msgCode + " No Exists");
				}
    			msgCode = msgCode || "";
    			msgParam = msgParam || "";

    			var msg = messagedata[msgCode] || msgCode;
    			var outmsg = msg.format(msgParam);

				switch (level) {
				case "trace":
				  tracelogger.trace(outmsg);
					break;
				case "debug":
				  debuglogger.debug(outmsg);
					break;
				case "info":
				  debuglogger.info(outmsg);
					break;
				case "warn":
				  debuglogger.warn(outmsg);
					break;
				case "error":
				  errlogger.error(outmsg);
					break;
				case "fatal":
				  errlogger.fatal(outmsg);
					break;
				}
    		}
    		var myLogger = {
    				trace:function(msgCode, msgParam){
    					logMsg("trace", msgCode, msgParam);
					},
					debug:function(msgCode, msgParam){
						logMsg("debug", msgCode, msgParam);
					},
					info:function(msgCode, msgParam){
						logMsg("info", msgCode, msgParam);
					},
					warn:function(msgCode, msgParam){
						logMsg("warn", msgCode, msgParam);
					},
					error:function(msgCode, msgParam){
						logMsg("error", msgCode, msgParam);
					},
					fatal:function(msgCode, msgParam){
						logMsg("fatal", msgCode, msgParam);
					}
    		}

        	var flowContext = this.context().flow;
          flowContext.set('logger',myLogger);
          node.log("[Loader Log4js Config Successfully] Log Config File:" + this.config);
          node.log("[Loader Log4js Config Successfully] Message Config File:" + this.message);
    	} catch(e){
    		node.error("[Loader Message Config Failed] No Such File:" + e.message);
    	}
    }
    RED.nodes.registerType("log4js",logger);
}